<?php
/**
 * 大赛报名
 */
namespace Beerus\Modules\DesignerCompetition2022\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Beerus\Modules\DesignerCompetition2022\Actions\EditSign;
use Beerus\Modules\DesignerCompetition2022\Actions\SignDelete;
use Beerus\Modules\DesignerCompetition2022\Actions\SyncFirstAudit;
use Doraemon\model\DesignerCompetition\DcAward;
use Doraemon\model\Member;
use Doraemon\model\ReDesignerCompetition\Sign\DcUserInfoHelper;
use Doraemon\model\ReDesignerCompetition\Sign\DcUserSignHelper;
use Doraemon\model\ReDesignerCompetition\Sign\Sign2022\DcUserSign;
use Doraemon\pockets\constInterface\Designer\DesignerCompetition2022;
use Doraemon\service\DesignerCompetition\Sign\Sign2022\Award;
use Doraemon\service\DesignerCompetition\Sign\Sign2022\SignInfo;
use Doraemon\tools\ActionLog;
use Doraemon\tools\Hhzurl;
use Doraemon\tools\ImgUrl;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Grid\Displayers\DropdownActions;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Doraemon\service\DesignerCompetition\Sign\Sign2022\ArticleCase;
use Beerus\Modules\DesignerCompetition2022\Actions\SyncFinalAudit;

class SignController extends Controller implements DesignerCompetition2022 {
    const PAGE_SIZE = 10;
    const AVERAGE_SPACE_LEVEL = 30;
    const STATUS_TXT = [
        1 => '已报名',
        2 => '待修改',
        3 => '已修改',
        9 => '已删除'
    ];

    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
    }

    /**
     * 大赛报名列表
     * @param Request $request
     * @param Content $content
     * @return Content
     */
    public function index(Request $request, Content $content) {
        $pageSize = $request->input('per_page', self::PAGE_SIZE);
        $page = $request->input('page', 1);
        $condition = $this->condition($request->all());
        // 查询报名总人数
        $signCnt = (DcUserSignHelper::getInstance(self::SIGN_YEAR))->getSignUserCntByCondition($condition);
        $tips = "<div class='alert alert-info'>共{$signCnt}个账号报名</div>";

        $tab = new Tab();
        $tab->addLink('报名作品列表', '/admin/DesignerCompetition2022/sign', true);
        $tab->addLink('报名信息列表', '/admin/DesignerCompetition2022/info');
        return $content
            ->header('大赛报名列表')
            ->row($tips)
            ->body($tab)
            ->row(self::indexGrid($condition, $page, $pageSize));
    }

    /**
     * 表格展示部分
     * @param $condition
     * @return Grid
     */
    public function indexGrid($condition, $page, $pageSize) {
        $total = (DcUserSignHelper::getInstance(self::SIGN_YEAR))->getSignCntByCondition($condition);
        $list = (DcUserSignHelper::getInstance(self::SIGN_YEAR))->getSignListByCondition($condition, $page, $pageSize);
        if (!empty($list)) {
            self::formatSignList($list);
        }
        $gridModel = new pGridDataModel($list, $total, [
            'perPage' => self::PAGE_SIZE,
        ]);

        // 获取单项奖
        $awardList = DcAward::getAllAwardListByAwardYear(self::SIGN_YEAR);
        $awardSelectList = [];
        foreach ($awardList as $awardItem) {
            if ($awardItem['award_type'] == self::AWARD_TYPE_LIST['main_award']) {
                $awardSelectList['main_award'][$awardItem['id']] = $awardItem['award_show_name'];
                continue;
            }
            if ($awardItem['award_type'] == self::AWARD_TYPE_LIST['single_award']) {
                $awardSelectList['single_award'][$awardItem['id']] = $awardItem['award_show_name'];
                continue;
            }
            if ($awardItem['award_type'] == self::AWARD_TYPE_LIST['brand_award']) {
                $awardSelectList['brand_award'][$awardItem['id']] = $awardItem['award_show_name'];
            }
        }
        $gridList = Admin::grid(
            $gridModel,
            function (Grid $grid) use ($gridModel, $awardSelectList) {
                $grid->paginate($gridModel->getPerPage());
                $grid->disableCreateButton();
                $grid->disableExport();
                $grid->disableRowSelector();

                $grid->filter(function (Grid\Filter $filter) use ($awardSelectList) {
                    $filter->disableIdFilter();

                    $filter->column(1 / 2, function ($filter) use ($awardSelectList) {
                        $filter->equal('user_type', '用户身份')->select(self::USER_TYPE_MAP);
                        $filter->equal('competition_area', '赛区')->select(self::COMPETITION_AREA_NAME);
                        $filter->equal('main_award', '类型')->select($awardSelectList['main_award']);
                        $filter->equal('audit_status', '评审结果')->select(self::AUDIT_STATUS_FILTER_MAP);
                        $filter->equal('recommend_organ', '合作机构')->select(self::RECOMMEND_ORGAN_LIST);
                        $filter->equal('id', '报名id');
                        $filter->equal('data_status', '数据状态')->select(self::STATUS_TXT);
                    });

                    $filter->column(1 / 2, function ($filter) use ($awardSelectList) {
                        $filter->equal('single_award', '同时报名单项奖')->select($awardSelectList['single_award']);
                        $filter->equal('brand_award', '同时报名品牌定制奖')->select($awardSelectList['brand_award']);
                        $options = ['' => '全部', '1' => '是', '2' => '否'];
                        $filter->equal('is_remark', '包含备注')->radio($options);
                        $filter->equal('admin_remark', '备注内容');
                        $filter->equal('uid', '用户uid');
                        $filter->equal('average_space', '人均面积')->select([
                            1 => '30平米/每人以下',
                            2 => '30平米/每人以上'
                        ]);
                    });
                    $filter->expand();
                });

                $grid->column('id', '报名id')->width(70);
                $grid->column('user_info', '用户信息')->width(140)->display(function () {
                    $userInfo[] = 'uid：' . $this->uid;
                    $userInfo[] = '昵称：<a href="https://frieza.haohaozhu.me/admin/user/Detail/' . $this->uid . '" target="_blank">' . $this->nick . '</a>';
                    $userInfo[] = '身份：' . $this->user_type;
                    return implode('<br/>', $userInfo);
                });

                $grid->column('competition_info', '参赛信息')->width(240)->display(function () {
                    $competition_info[] = '城市：' . $this->city;
                    $competition_info[] = '类型：<br/>' . implode('<br/>', $this->main_award);
                    if (isset($this->single_award)) {
                        $competition_info[] = '单项：<br/>' . implode('<br/>', $this->single_award);
                    }
                    if (isset($this->brand_award)) {
                        $competition_info[] = '品牌：<br/>' . implode('<br/>', $this->brand_award);
                    }
                    $competition_info[] = '报名时间：' . $this->sign_time;
                    return implode('<br/>', $competition_info);
                });
//
                $grid->column('work_link', '作品链接')->width(210)->display(function () {
                    $open = isset($this->work_name) ? '<a class="fa " href="javascript:layer.open(
                        {
                            type: 2,
                            title: \'预览\', 
                            maxmin: true, 
                            area: [\'350px\', \'700px\'],
                            fixed: false,
                            offset: \'r\',
                            content: \'' . $this->link . '\' 
                        });">' . htmlentities($this->work_name) . '</a>' : "";
                    $img = "<img width='200' height='200' src='{$this->work_pic_url}'>";
                    $download = "<a href='/admin/DesignerCompetition2022/download/{$this->id}'
                    style='color: darkblue'>下载图片</a>";
                    return implode('<br/>', [$img, $open, $download]);

                });
                $grid->column('work_info', '作品信息')->width(300)->display(function () {
                    $work_info = [];
                    $work_info[] = '居室：' . self::ROOM_NUM_TYPE_NAME[$this->room_num_type];
                    $work_info[] = '总造价：' . $this->total_price . '万元';
                    $work_info[] = '地区：' . $this->house_area;
                    $work_info[] = '常住人口：' . $this->people_scale .'人';
                    $work_info[] = '家庭关系：' . $this->family_relation;
                    $work_info[] = '人均面积：' . $this->average_space . '平米/人';
                    $work_info[] = '项目完成时间：' . $this->finish_date;
                    $work_info[] = '使用面积：' . $this->house_space . '平米';
                    $work_info[] = '合作机构：' . ($this->recommend_organ ? self::RECOMMEND_ORGAN_LIST[$this->recommend_organ] : '无');
                    return implode('<br/>', $work_info);
                });

                $grid->column('audit_status', '评审结果')
                    ->width(400)
                    ->checkbox(self::AUDIT_STATUS_MAP);
                $grid->column('data_status', '数据状态')->width(150)->display(function () {
                    return self::STATUS_TXT[$this->data_status];
                });
                $grid->column('admin_remark', '备注')->width(200)->editable();

                $grid->setActionClass(DropdownActions::class);
                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableDelete();
                    $actions->disableEdit();
                    $actions->disableView();
                    $actions->add(new EditSign);
                    if ($this->row['data_status'] != DcUserSign::STATUS_DELETE) {
                        $actions->add(new SignDelete);
                    }
                    $actions->add(new SyncFirstAudit);
                    $actions->add(new SyncFinalAudit);
                });
            }
        );

        return $gridList;
    }

    private function condition($request) {
        $response = [];
        if (!empty($request['uid'])) {
            $response['uid'] = $request['uid'];
        }
        if (!empty($request['user_type'])) {
            $response['user_type'] = $request['user_type'];
        }
        if (!empty($request['competition_area'])) {
            $response['competition_area'] = $request['competition_area'];
        }
        if (!empty($request['main_award'])) {
            $response['main_award'] = $request['main_award'];
        }
        if (!empty($request['single_award'])) {
            $response['single_award'] = $request['single_award'];
        }
        if (!empty($request['brand_award'])) {
            $response['brand_award'] = $request['brand_award'];
        }
        if (!empty($request['recommend_organ'])) {
            $response['recommend_organ'] = $request['recommend_organ'];
        }
        if (isset($request['audit_status']) && $request['audit_status'] !== '') {
            $response['audit_status'] = $request['audit_status'];
        }
        // '' = 全部；1=有备注；2=没有备注
        if (!empty($request['is_remark'])) {
            $response['is_remark'] = $request['is_remark'];
        }
        if (!empty($request['admin_remark'])) {
            $response['admin_remark'] = $request['admin_remark'];
        }
        if (!empty($request['id'])) {
            $response['id'] = $request['id'];
        }
        if (!empty($request['average_space'])) {
            if ($request['average_space'] == 1) {
                $response['average_space'] = '<='.self::AVERAGE_SPACE_LEVEL;
            } else {
                $response['average_space'] = '>'.self::AVERAGE_SPACE_LEVEL;
            }
        }
        if (!empty($request['data_status'])) {
            $response['data_status'] = $request['data_status'];
        }
        return $response;
    }

    public function save(Request $request, $id)
    {
        $pjax = true;
        $status = true;
        $name = $request->input('name');
        $value = $request->input('value');
        $audit_status = $request->input('audit_status', '');

        $message = "修改成功";
        try {
            if (isset($name) && isset($value)) {
                switch ($name) {
                    case 'admin_remark':
                        $pjax = false;
                        if (mb_strlen($value) > 300) {
                            throw new \Exception('最多300字');
                        }
                        (DcUserSignHelper::getInstance())->updateSign($id, ['admin_remark' => $value]);
                        break;
                    default:
                        throw new \Exception('未开发功能');
                }
            } else {
                $audit_status = empty($audit_status) ? '' : implode(',', $audit_status);
                $aSignInfo = (DcUserSignHelper::getInstance())->getSignItemById($id);
                (DcUserSignHelper::getInstance())->updateSign($id, ['audit_status' => $audit_status]);
                ActionLog::log(Admin::user()->id,
                    [
                        'admin_id' => Admin::user()->id,
                        'old_sign_info' => $aSignInfo,
                        'new_audit_status' => $audit_status
                    ], ActionLog::DC_EDIT_SIGN_AUDIT_STATUS_2022);
            }
        } catch (\Exception $e) {
            $status = false;
            $message = $e->getMessage();

            if (!$pjax) {
                return response()->json(['errors' => [$message]], 422);
            }
        }
        return response()->json(compact('message', 'status'));
    }

    public function download($id) {
        // 查询当前报名作品的图片信息
        $sign_info = (DcUserSignHelper::getInstance())->getSignItemById($id);
        $work_info = json_decode($sign_info['work_info'], true);
        $photos = [];
        if (!empty($work_info['plane_photo_before'])) {
            $photos[] = ImgUrl::getUrlNotSWater(ImgUrl::APPTYPE_APP, $work_info['plane_photo_before']['pic_id'], ImgUrl::IMAGE_SIZE_ORI_NPHONE);
        }
        if (!empty($work_info['plane_photo_after'])) {
            $photos[] = ImgUrl::getUrlNotSWater(ImgUrl::APPTYPE_APP, $work_info['plane_photo_after']['pic_id'], ImgUrl::IMAGE_SIZE_ORI_NPHONE);
        }
        if (!empty($work_info['live_photos'])) {
            foreach ($work_info['live_photos'] as $item) {
                $photos[] = ImgUrl::getUrlNotSWater(ImgUrl::APPTYPE_APP, $item['pic_id'], ImgUrl::IMAGE_SIZE_ORI_NPHONE);
            }
        }
        if (!empty($work_info['detail_photos'])) {
            foreach ($work_info['detail_photos'] as $item) {
                $photos[] = ImgUrl::getUrlNotSWater(ImgUrl::APPTYPE_APP, $item['pic_id'], ImgUrl::IMAGE_SIZE_ORI_NPHONE);
            }
        }
        if (!empty($work_info['analysis_photos'])) {
            foreach ($work_info['analysis_photos'] as $item) {
                $photos[] = ImgUrl::getUrlNotSWater(ImgUrl::APPTYPE_APP, $item['pic_id'], ImgUrl::IMAGE_SIZE_ORI_NPHONE);
            }
        }

        $save_path = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'sign_image' . DIRECTORY_SEPARATOR . $id;

        if (!is_dir($save_path)) {
            mkdir($save_path, 0777, true);
        }

        foreach ($photos as $url) {
            $file_name = $save_path . DIRECTORY_SEPARATOR . md5($url) . '.jpeg';
            if (!file_exists($file_name)) {
                file_put_contents($file_name, file_get_contents($url));
            }
        }

        // 压缩打包文件
        $outputs = [];
        exec("cd {$save_path}; zip -r {$save_path} ". DIRECTORY_SEPARATOR ."image.zip ./ ", $outputs, $rc);
        $file = "/tmp/sign_image/{$id}.zip";
        $fp = fopen($file, "r");
        if (file_exists($file)) {
            exec("rm -rf  {$save_path}". DIRECTORY_SEPARATOR, $outputs, $rc);
            ob_end_clean();

            $file_size = filesize($file);
            header("Content-type:application/octet-stream");
            header("Accept-Ranges:bytes");
            header("Accept-Length:" . $file_size);
            header("Content-Disposition: attachment;filename={$id}.zip");

            $buffer = 1024;
            $file_count = 0;

            while (!feof($fp) && $file_count < $file_size) {
                $file_con = fread($fp, $buffer);
                $file_count += $buffer;
                echo $file_con;
            }

            fclose($fp);
            if ($file_count >= $file_size) {
                unlink($file);
            }

            return response()->json(['errors' => ['no']], 422);
        }
    }

    public static function formatSignList(&$list) {
        $userIds = array_column($list, 'uid');
        $memberInfo = Member::getUsers($userIds);
        $awardRet = (new Award)->getAllAwardListWithTypeGroup();
        foreach ($list as &$item) {
            $item['work_info'] = json_decode($item['work_info'], true);
            // 用户信息
            $item['nick'] = empty($memberInfo[$item['uid']]['nick']) ? '' : $memberInfo[$item['uid']]['nick'];
            $item['user_type'] = self::USER_TYPE[$memberInfo[$item['uid']]['type']];

            // 参赛信息
            $item['competition_area'] = self::COMPETITION_AREA_NAME[$item['competition_area']];
            $competitionInfo = (DcUserInfoHelper::getInstance())->getItemByUid($item['uid']);
            $item['city'] = \Hhz\AdministrativeRegion\Region::getAreaDetailByCode($competitionInfo['city']);
            $item = array_merge($item, Award::getAllAwardName($item['award_ids'], $awardRet));
            $item['sign_time'] = date('Y-m-d H:i:s', $item['add_time']);
            $item['sign_year'] = date('Y', $item['add_time']);

            // 作品链接
            $item['work_pic_url'] = (new SignInfo())->getWorkCoverUrl($item['work_info']['live_photos']); // 取实景作品的第一条

            $item['link'] = Hhzurl::getDomain() . "/designer/game/2022/detail?sign_id={$item['id']}";

            // 作品信息
            (new ArticleCase())->getArticleInfo($item['article_id'], $item['work_info'], $item['article_from']);
            $item['house_area'] = \Hhz\AdministrativeRegion\Region::getAreaDetailByCode($item['work_info']['house_area']);
            $houseSpace = preg_replace('/[平米|平方米|平|平方|㎡]/', '', $item['work_info']['house_space']);
            $item['family_relation'] = $item['work_info']['family_relation'];
            $item['people_scale'] = $item['work_info']['people_scale'];
            $item['total_price'] = $item['work_info']['total_price'];
            $item['finish_date'] = $item['work_info']['finish_date'];
            $item['house_space'] = $houseSpace;
            $item['room_num_type'] = $item['work_info']['room_num_type'];
            $item['audit_status'] = $item['audit_status'] ? explode(',', $item['audit_status']) : 0;
        }
    }
}
